﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
using LinkPad.Helpers;

namespace LinkPad
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage
    {
        #region Constructors

        public MainPage()
        {
            InitializeComponent();

            RecentFiles = new ObservableCollection<StorageFile>();

            LoadRecentObjects();

            RecentItems.SelectionChanged += RecentItemsOnSelectionChanged;

            DataContext = this;
        }

        #endregion

        #region Properties

        public ObservableCollection<StorageFile> RecentFiles { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void BtnNewOnClick(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof (DiagramPage));
        }

        private void BtnLoadOnClick(object sender, RoutedEventArgs e)
        {
            Load();
        }

        private void BtnClearOnClick(object sender, RoutedEventArgs e)
        {
            UIHelper.ClearTempRecentLRU();
            LoadRecentObjects();
        }

        private async void LoadRecentObjects()
        {
            RecentFiles.Clear();
            await UIHelper.VerifyRecentLRU();
            var list = StorageApplicationPermissions.MostRecentlyUsedList;
            var mruEntries = list.Entries;
            foreach (var entry in mruEntries.Reverse())
            {
                var token = entry.Token;
                var file = await list.GetFileAsync(token);
                RecentFiles.Insert(0, file);
            }
        }

        private void RecentItemsOnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItems = e.AddedItems;
            if (selectedItems.Count > 0)
            {
                var selected = selectedItems[0];
                var file = selected as StorageFile;
                Frame.Navigate(typeof(DiagramPage), file);
            }
        }

        private async void Load()
        {
            if (!UIHelper.EnsureUnsnapped())
            {
                // TODO notify the user
                return;
            }

            var filePicker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            filePicker.FileTypeFilter.Add(".lnp");
            var file = await filePicker.PickSingleFileAsync();

            if (file == null)
            {
                // TODO notify the user
                return;
            }

            Frame.Navigate(typeof (DiagramPage), file);
        }

        #endregion
    }
}
